/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.hk.shop.web.shop;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.ServiceException;
import com.thinkgem.jeesite.common.utils.*;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.hk.shop.entity.product.HkShopProduct;
import com.thinkgem.jeesite.modules.hk.shop.entity.product.HkShopProductSku;
import com.thinkgem.jeesite.modules.hk.shop.entity.shop.HkShopCoupon;
import com.thinkgem.jeesite.modules.hk.shop.entity.shop.HkUserShop;
import com.thinkgem.jeesite.modules.hk.shop.entity.shop.HkUserShopCouponOrder;
import com.thinkgem.jeesite.modules.hk.shop.service.product.HkShopProductService;
import com.thinkgem.jeesite.modules.hk.shop.service.product.HkShopProductSkuService;
import com.thinkgem.jeesite.modules.hk.shop.service.shop.HkShopCouponService;
import com.thinkgem.jeesite.modules.hk.shop.service.shop.HkUserShopCouponOrderService;
import com.thinkgem.jeesite.modules.hk.sys.entity.user.HkUser;
import com.thinkgem.jeesite.modules.hk.sys.service.user.HkUserService;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Map;

/**
 * 优惠券Controller
 *
 * @author 李欣荣
 * @version 2018-09-27
 */
@Controller
@RequestMapping(value = "${adminPath}/shop/shop/hkShopCoupon")
public class HkShopCouponController extends BaseController {

    private static final String wxPayAPI = "v1/pay/weixinpay";
    private static final BigDecimal bigDecimal = new BigDecimal("2");
    private static final BigDecimal bigDecimal2 = new BigDecimal("100");
    private static final BigDecimal bigDecimal3 = new BigDecimal("600");


    @Autowired
    private HkShopCouponService hkShopCouponService;
    @Autowired
    private HkShopProductService hkShopProductService;
    @Autowired
    private HkUserShopCouponOrderService hkUserShopCouponOrderService;
    @Autowired
    private HkUserService hkUserService;

    @ModelAttribute
    public HkShopCoupon get(@RequestParam(required = false) String id) {
        HkShopCoupon entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = hkShopCouponService.get(id);
        }
        if (entity == null) {
            entity = new HkShopCoupon();
            entity.setBisId(IdGen.uuid());
        }
        return entity;
    }

    @RequiresPermissions("shop:shop:hkShopCoupon:view")
    @RequestMapping(value = {"list", ""})
    public String list(HkShopCoupon hkShopCoupon, HttpServletRequest request, HttpServletResponse response, Model model) {
        HkShopProduct hkShopProduct = new HkShopProduct();
        HkUserShop hkUserShop = new HkUserShop();
        hkUserShop.setId(UserUtils.getShopId());
        hkShopProduct.setShop(hkUserShop);
        hkShopCoupon.setProduct(hkShopProduct);
        Page<HkShopCoupon> page = hkShopCouponService.findPage(new Page<HkShopCoupon>(request, response), hkShopCoupon);
        model.addAttribute("page", page);
        return "hk/shop/shop/hkShopCouponList";
    }

    @RequiresPermissions("shop:shop:hkShopCoupon:view")
    @RequestMapping(value = "form")
    public String form(HkShopCoupon hkShopCoupon, Model model) {
        model.addAttribute("hkShopCoupon", hkShopCoupon);
        return "hk/shop/shop/hkShopCouponForm";
    }

    @RequiresPermissions("shop:shop:hkShopCoupon:edit")
    @RequestMapping(value = "save")
    public String save(HkShopCoupon hkShopCoupon, Model model, RedirectAttributes redirectAttributes) {
        boolean flag = false;
        if (!beanValidator(model, hkShopCoupon)) {
            return form(hkShopCoupon, model);
        }

        if (StringUtils.isBlank(UserUtils.getShopId())) {
            addMessage(redirectAttributes, "登录超时，请重新登录！");
            return "redirect:" + Global.getFrontPath();
        }

        try {

            hkShopCoupon.setIsNewRecord(true);
            hkShopCoupon.setId(hkShopCoupon.getBisId());
            hkShopCouponService.insert(hkShopCoupon);
            flag = true;

            if (flag) {
                addMessage(redirectAttributes, "保存优惠券成功");
            } else {
                addMessage(redirectAttributes, "保存优惠券失败");
            }
        } catch (Exception e) {
            model.addAttribute("hkShopCoupon", hkShopCoupon);
            addMessage(redirectAttributes, "乐币不足，请先充值！");
            e.printStackTrace();
        }

        return "redirect:" + Global.getAdminPath() + "/shop/shop/hkShopCoupon/?repage";
    }


    /**
     * 校验用户乐币是否充足
     *
     * @return
     */
    @RequestMapping(value = "isIntegral")
    @ResponseBody
    public String isIntegral(HttpServletRequest request) {
        String integral = request.getParameter("integral");
        User manage = UserUtils.getUser();
        //查找HkUser乐币
        try {
            HkUser hkUser = hkShopCouponService.getHkUser(manage.getId());
            if (hkUser.getIntegral() == null || hkUser.getIntegral().equals("")) {
                return "fail";
            } else {
                if (Double.parseDouble(hkUser.getIntegral()) <= 0 || Double.parseDouble(hkUser.getIntegral()) < Double.parseDouble(integral)) {
                    return "fail";
                } else {
                    return "success";
                }
            }
        } catch (Exception e) {
            return "fail";
        }
    }


    @RequiresPermissions("shop:shop:hkShopCoupon:edit")
    @RequestMapping(value = "delete")
    public String delete(HkShopCoupon hkShopCoupon, RedirectAttributes redirectAttributes) {
        hkShopCouponService.delete(hkShopCoupon);
        addMessage(redirectAttributes, "删除优惠券成功");
        return "redirect:" + Global.getAdminPath() + "/shop/shop/hkShopCoupon/?repage";
    }

    /**
     * 计算乐币
     *
     * @param productId          商品ID
     * @param model
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "getReckonIntegral")
    @ResponseBody
    public String getReckonIntegral(String productId, Model model, RedirectAttributes redirectAttributes) {
        String integral = null;

        if (StringUtils.isBlank(UserUtils.getShopId())) {
            addMessage(redirectAttributes, "登录超时，请您重新登录！");
            return "redirect:" + Global.getFrontPath();
        }

        if (!StringUtils.isBlank(productId)) {
            //计算乐币
            HkShopProduct hkShopProduct = hkShopProductService.getPrice(productId);
            if (hkShopProduct != null && StringUtils.isNotBlank(hkShopProduct.getIntegral())) {
                if (new BigDecimal(hkShopProduct.getIntegral()).compareTo(bigDecimal3) == -1) {
                    BigDecimal price = new BigDecimal(hkShopProduct.getIntegral());
                    integral = (price.divide(bigDecimal, 0)).multiply(bigDecimal2).toString();
                } else {
                    integral = (bigDecimal3.divide(bigDecimal, 0)).multiply(bigDecimal2).toString();
                }
            } else {
                return null;
            }
        } else {
            return null;
        }
        return integral;
    }


    /**
     * 导出优惠券数据
     *
     * @param hkShopCoupon
     * @param request
     * @param response
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("shop:shop:hkShopCoupon:view")
    @RequestMapping(value = "export", method = RequestMethod.POST)
    public String exportFile(HkShopCoupon hkShopCoupon, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            HkShopProduct hkShopProduct = new HkShopProduct();
            HkUserShop hkUserShop = new HkUserShop();
            hkUserShop.setId(UserUtils.getShopId());
            hkShopProduct.setShop(hkUserShop);
            hkShopCoupon.setProduct(hkShopProduct);
            String fileName = "优惠券数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            Page<HkShopCoupon> page = hkShopCouponService.findCoupon(new Page<HkShopCoupon>(request, response, -1), hkShopCoupon);
            new ExportExcel("优惠券数据", HkShopCoupon.class).setDataList(page.getList()).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导出优惠券失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + adminPath + "/shop/shop/hkShopCoupon/list?repage";
    }


    /**
     * 获取微信支付二维码
     *
     * @param integral
     * @param productId
     * @param couponId
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "getWxCodeUrl", method = RequestMethod.GET)
//    @ResponseBody
    public String getWxCodeUrl(String money, String integral, String productId, String couponId, RedirectAttributes redirectAttributes, ModelMap modelMap) {

        String result = "";
        HkUserShopCouponOrder hkUserShopCouponOrder = new HkUserShopCouponOrder();
        Map<String, Object> mapParam = Maps.newHashMap();

        Long orderNumber = OrderUtil.getOrder();

        //计算支付金额（改需求弃用）
        if (StringUtils.isNotBlank(integral)) {
            BigDecimal bigIntegral = new BigDecimal(integral);
            String totalFee = (bigIntegral.divide(bigDecimal2)).divide(bigDecimal).toString();
        }


        //根据金额取乐币数
        if (money.equals("30.00")) {
            integral = "3000";
        } else if (money.equals("50.00")) {
            integral = "5000";
        } else if (money.equals("100.00")) {
            integral = "10000";
        } else if (money.equals("200.00")) {
            integral = "20000";
        } else {
            integral = "";
        }

        modelMap.addAttribute("money", money);
        modelMap.addAttribute("integral", integral);
        modelMap.addAttribute("orderNumber", orderNumber.toString());

//        if (StringUtils.isNotBlank(integral) && StringUtils.isNotBlank(productId) && StringUtils.isNotBlank(couponId)) {
        if (StringUtils.isNotBlank(integral)) {

            try {
                HkUser hkUser = hkShopCouponService.getHkUser(UserUtils.getUser().getId());
                hkUserShopCouponOrder.setUser(hkUser);
                hkUserShopCouponOrder.setProduct(new HkShopProduct(productId));
                hkUserShopCouponOrder.setCoupon(new HkShopCoupon(couponId));
                hkUserShopCouponOrder.setOrderNumber(orderNumber.toString());
                hkUserShopCouponOrder.setIntegral(integral);
//            hkUserShopCouponOrder.setTotal_fee(money);
                hkUserShopCouponOrder.setTotal_fee("0.01");
                hkUserShopCouponOrderService.save(hkUserShopCouponOrder);

                mapParam.put("ordersId", orderNumber.toString());
                mapParam.put("type", 3);
                mapParam.put("backUrl", "");
                result = HttpClientUtil.httpRequestToString(Global.getWxPayBaseDir() + wxPayAPI, "get", mapParam, null);
                JSONObject jsonObject = JSONObject.parseObject(result);
                String code = jsonObject.get("code").toString();
                if (code.equals("0")) {
                    if (jsonObject.getString("data") != null) {
                        JSONObject json = JSONObject.parseObject(jsonObject.getString("data"));
                        result = json.getString("codeurl");
                        modelMap.addAttribute("codeUrl", result);
//                        mapParam.put("codeUrl", result);
//                    } else {
                        mapParam.put("codeUrl", "ErrParam");
                    }
                }
            } catch (Exception e) {
                addMessage(redirectAttributes, "保存优惠券错误，请稍后重试！");
                e.printStackTrace();
            }
        } else {
            mapParam.put("codeUrl", "ErrParam");
        }
        return "hk/shop/pay/wxPayCode";
    }


    /**
     * 校验支付结果
     *
     * @param orderNumber
     * @param integral
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "voliPayResult")
    @ResponseBody
    public String voliPayResult(String orderNumber, String integral, RedirectAttributes redirectAttributes) {
        HkUserShopCouponOrder hkUserShopCouponOrder = hkUserShopCouponOrderService.getWxPayResult(orderNumber);
        if (StringUtils.isNotBlank(hkUserShopCouponOrder.getResult_code()) && ("SUCCESS").equals(hkUserShopCouponOrder.getResult_code())) {
            //修改用户乐币
            try {
                hkUserService.addIntegral(UserUtils.getUser().getId(), Double.parseDouble(integral));
                addMessage(redirectAttributes, "订单支付成功，请保存优惠券信息！");
                return "success";
            } catch (NumberFormatException e) {
                addMessage(redirectAttributes, "订单未支付，请支付后添加优惠券！");
                e.printStackTrace();
                return "fail";
            }
        } else {
            return "fail";
        }
    }


    @RequestMapping(value = "goWXPay")
    public String goWXPay() {
        return "hk/shop/pay/wxPay";
    }

}

